package com.loong.common.redis;

import com.loong.common.redis.function.TransactionalFunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

@Component
public class RedisTools {

    private static CommonRedisTemplate redisTemplate;

    private static StringRedisTemplate stringRedisTemplate;

    @Autowired
    public void setRedisTemplate(CommonRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate redisTemplate) {
        this.stringRedisTemplate = redisTemplate;
    }

    public static <T> CommonValueOperations<String, T> valueOperations() {
        return redisTemplate.getValueOps();
    }

    public static ValueOperations<String, String> stringOperations() {
        return stringRedisTemplate.opsForValue();
    }

    public static <T> CommonHashOperations<String, String, T> hashOperations() {
        return redisTemplate.getHashOperations();
    }

    public static CommonRedisTemplate template(){
        return redisTemplate;
    }

    public static <T> CommonSetOperations<String, T> setOperations() {
        return redisTemplate.getSetOps();
    }

    /**
     * redis 事务执行器
     *
     * @param supplier
     * @param <T>
     * @return
     */
    public static <T> T doTransaction(TransactionalFunction<T> supplier) {
        T execute = (T) redisTemplate.execute(new SessionCallback<T>() {
            public T execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                try {
                    T t = supplier.doTransaction();
                    operations.exec();
                    return t;
                } catch (Exception e) {
                    operations.discard();
                    throw new RuntimeException(e);
                }
            }
        });
        return execute;
    }
    public static long bitCount(final String key) {
        return (long) redisTemplate.<Long>execute((RedisCallback<Long>) connection -> connection.bitCount(key.getBytes()));
    }
}
